package com.example.taobaounion.view_component;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.example.taobaounion.R;

public class AutoLoopViewPager extends ViewPager {

    public static final long DEFAULT_INTERVAL = 3000;

    private long mInterval = DEFAULT_INTERVAL;

    // switch
    boolean isLoop = true;

    public AutoLoopViewPager(@NonNull Context context) {
        this(context, null);
    }

    public AutoLoopViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        initVariable(context, attrs);
    }

    private void initVariable(Context context, AttributeSet attrs) {
        @SuppressLint("CustomViewStyleable") TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AutoLoopStyle);
        mInterval = typedArray.getInteger(R.styleable.AutoLoopStyle_interval, (int) DEFAULT_INTERVAL);
        // 重用回收
        typedArray.recycle();
    }


    public void startLoop() {
        post(mRunnable);
        isLoop = true;
    }

    Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            int currentItem = getCurrentItem();
            currentItem++;
            setCurrentItem(currentItem);
            postDelayed(this, mInterval);
        }
    };

    public void stopLoop() {
        removeCallbacks(mRunnable);
        isLoop = false;
    }
}
